<template>
  <a-modal
    :title="isVerifiedPhone ? '绑定手机' : '手机验证'"
    :visible="changePhoneModalVisible"
    :confirm-loading="false"
    :ok-text="isVerifiedPhone ? '确定' : '验证'"
    cancel-text="取消"
    @ok="handleChangePhoneModalOk"
    @cancel="closeChangePhoneModal"
  >
    <a-form
      :form="form"
      @submit="handleChangePhoneModalOk"
      @submit.native.prevent
    >
      <div v-if="!isVerifiedPhone">
        <p style="letter-spacing: 1px; margin-bottom: 24px;">
          为了确保您为本人操作，请先进行安全验证。
        </p>
        <p style="color: #5d637e; font-weight: 500; letter-spacing: 1px;">
          验证方式
        </p>
        <a-form-item>
          <a-input
            disabled
            :value="phone.replace(/^(\d{3})\d{6}(\d+)/, '$1******$2')"
            style="height: 40px; margin: 0 0 5px;"
          ></a-input>
        </a-form-item>
        <a-form-item>
          <div style="display: flex;">
            <a-input
              v-decorator="[
                'phoneCaptcha',
                {
                  rules: [
                    { required: true, message: '请输入您的手机验证码！' },
                  ],
                },
              ]"
              style="height: 40px; margin: 5px 0;"
              placeholder="请输入6位验证码"
            />
            <a-button
              v-show="show"
              style="height: 40px; margin: 5px; margin-right: 0;"
              @click="sendCaptcha"
              >发送验证码</a-button
            >
            <span
              v-show="!show"
              slot="addonAfter"
              style="
                height: 40px;
                line-height: 1.5;
                margin: 5px;
                margin-right: 0;
                width: 100px;
              "
              disabled
            >
              {{ count }}秒之后可以重新发送
            </span>
          </div>
          <div
            v-if="captchaCode !== ''"
            style="display: flex; margin-bottom: 8px;"
          >
            <a-input
              v-model="captcha"
              style="height: 40px; margin: 0 0 5px;"
              placeholder="请输入验证码"
            ></a-input>
            <img
              style="height: 40px; margin-left: 5px; width: 102px;"
              alt=""
              :src="`data:text/css;base64,${captchaCode}`"
              @click="refreshCaptchaCode"
            />
          </div>
        </a-form-item>
        <p
          style="
            color: #222432;
            font-size: 12px;
            letter-spacing: 1.12px;
            margin-bottom: 2px;
          "
        >
          没收到短信验证码？
        </p>
        <p
          style="
            color: #222432;
            font-size: 12px;
            letter-spacing: 1.12px;
            line-height: 18px;
            opacity: 0.5;
          "
        >
          1、网络通讯异常可能会造成短信丢失，请重新获取或稍后再试。<br />
          2、请核实手机是否已欠费停机，或者屏蔽了系统短信。<br />
          <!-- 3、如果手机已丢失或停用，请选择其他验证方式。 -->
        </p>
      </div>
      <div v-if="isVerifiedPhone">
        <p style="letter-spacing: 1px; margin-bottom: 24px;">
          请输入您要绑定的手机号
        </p>
        <p style="color: #5d637e; font-weight: 500; letter-spacing: 1px;">
          验证方式
        </p>
        <a-form-item>
          <a-input
            v-decorator="[
              'newPhone',
              {
                rules: [{ required: true, validator: validatePhone }],
              },
            ]"
            style="height: 40px; margin: 0 0 5px;"
            placeholder="请输入手机号"
          ></a-input>
        </a-form-item>
        <a-form-item>
          <div style="display: flex;">
            <a-input
              v-decorator="[
                'newPhoneCaptcha',
                {
                  rules: [
                    { required: true, message: '请输入您的手机验证码！' },
                  ],
                },
              ]"
              style="height: 40px; margin: 5px 0;"
              placeholder="请输入6位验证码"
            />
            <a-button
              v-show="show"
              style="height: 40px; margin: 5px; margin-right: 0;"
              @click="sendCaptcha"
              >发送验证码</a-button
            >
            <span
              v-show="!show"
              slot="addonAfter"
              style="
                height: 40px;
                line-height: 1.5;
                margin: 5px;
                margin-right: 0;
                width: 100px;
              "
              disabled
            >
              {{ count }}秒之后可以重新发送
            </span>
          </div>
          <div
            v-if="captchaCode !== ''"
            style="display: flex; margin-bottom: 8px;"
          >
            <a-input
              v-model="captcha"
              style="height: 40px; margin: 0 0 5px;"
              placeholder="请输入验证码"
            ></a-input>
            <img
              style="height: 40px; margin-left: 5px; width: 102px;"
              alt=""
              :src="`data:text/css;base64,${captchaCode}`"
              @click="refreshCaptchaCode"
            />
          </div>
        </a-form-item>
        <p
          style="
            color: #222432;
            font-size: 12px;
            letter-spacing: 1.12px;
            margin-bottom: 2px;
          "
        >
          注意
        </p>
        <p
          style="
            color: #222432;
            font-size: 12px;
            letter-spacing: 1.12px;
            line-height: 18px;
            opacity: 0.5;
          "
        >
          1、一个手机可以绑定或登陆1个见微大数据平台账户。<br />
          2、您可以使用此手机号进行找回密码等敏感操作。<br />
          3、请勿随意泄露手机号，以防被不法分子利用，骗取账号信息。
        </p>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="display: none;"
          >登录</a-button
        >
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import { getImageCaptchaCode, phoneBind, phoneBindChange } from '@/api/sms'
import { bind, bindChange } from '@/api/user'

@Component
export default class ChangePhone extends Vue {
  @Prop() changePhoneModalVisible!: boolean
  @Prop() phone!: string
  private form: any
  // 图片验证码base64编码
  private captchaCode: string = ''
  // 图片验证码输入
  private captcha: string = ''
  // 是否已经验证手机
  private isVerifiedPhone: boolean = false

  public initModalValue() {
    this.isVerifiedPhone = this.phone === ''
  }

  public resetModalValue() {
    this.form.setFieldsValue({
      phoneCaptcha: '',
    })
    if (this.isVerifiedPhone) {
      this.form.setFieldsValue({
        newPhone: '',
        newPhoneCaptcha: '',
      })
    }
    this.captcha = ''
    this.captchaCode = ''
    this.isVerifiedPhone = this.phone === ''
    this.$emit('close-change-phone-modal')
  }

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'phone_form' })
  }

  public closeChangePhoneModal() {
    this.resetModalValue()
  }

  private show: boolean = true
  private count: number = 0
  private timer: any = null
  public async sendCaptcha() {
    // 间隔60秒
    const TIME_COUNT = 60
    let result
    if (this.isVerifiedPhone) {
      result = await phoneBind(
        this.captcha === ''
          ? {
              data: { phone: this.form.getFieldValue('newPhone') },
            }
          : {
              data: {
                phone: this.form.getFieldValue('newPhone'),
                captchaCode: this.captcha,
              },
            }
      )
    } else {
      result = await phoneBindChange(
        this.captcha === ''
          ? {
              data: {
                captchaCode: '',
              },
            }
          : {
              data: {
                captchaCode: this.captcha,
              },
            }
      )
    }
    // 根据返回code决定前端
    if (result.data.code === 100) {
      this.$message.success('短信发送成功')
      // 发送成功，设置60秒间隔才能发送
      this.count = TIME_COUNT
      this.show = false
      this.timer = setInterval(() => {
        if (this.count > 0 && this.count <= TIME_COUNT) {
          this.count -= 1
        } else {
          this.show = true
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    } else if (
      // 需要请求验证码的情况
      result.data.code === 20016 ||
      result.data.code === 20015 ||
      this.captchaCode !== ''
    ) {
      this.$message.error(result.data.message)
      const captchaResult = await getImageCaptchaCode({
        data: this.isVerifiedPhone
          ? this.form.getFieldValue('newPhone')
          : this.phone,
      })
      this.captchaCode = captchaResult.data.result
    } else {
      this.$message.error(result.data.message)
    }
  }

  // 刷新图片验证码
  public async refreshCaptchaCode() {
    const result = await getImageCaptchaCode({
      data: this.isVerifiedPhone
        ? this.form.getFieldValue('newPhone')
        : this.phone,
    })
    this.captchaCode = result.data.result
  }

  public async handleChangePhoneModalOk() {
    if (this.isVerifiedPhone) {
      this.form.validateFields(
        ['newPhone', 'newPhoneCaptcha'],
        async (error: Error, values: any) => {
          if (!error) {
            const result = await bind({
              data: {
                phone: values.newPhone,
                code: values.newPhoneCaptcha,
              },
            })
            if (result.data.code === 100) {
              this.$message.success('更改手机号成功!')
              this.$emit('get-user-info')
              this.resetModalValue()
            } else {
              this.$message.error(result.data.message)
            }
          } else {
            console.log(error)
          }
        }
      )
    } else {
      this.form.validateFields(
        ['phoneCaptcha'],
        async (error: Error, values: any) => {
          if (!error) {
            const result = await bindChange({
              data: {
                code: values.phoneCaptcha,
              },
            })
            if (result.data.code === 100) {
              this.isVerifiedPhone = true
              this.show = true
              this.captcha = ''
              this.captchaCode = ''
            } else {
              this.$message.error(result.data.message)
            }
          } else {
            console.log(error)
          }
        }
      )
    }
  }

  // 手机号格式rule
  public validatePhone(rule: any, value: any, callback: any) {
    if (!value) {
      callback('请输入您的手机号！')
    } else if (!/^1[3-9]\d{9}$/.test(value)) {
      callback('手机号格式错误!')
    } else {
      callback()
    }
  }
}
</script>

<style lang="less" scoped>
// 行间距
.ant-form-item {
  margin-bottom: 0;
}

/deep/ .ant-form-explain {
  margin-left: 10px !important;
  text-align: left;
}
</style>
